<template>
	<el-container>
		<el-header style="height: auto;">
			<div class="mb-4 flex justify-between items-center">
				<el-button type="primary" @click="add">
					<i class="el-icon-plus mr-2" />新建文件
				</el-button>

			</div>
			<div align="right">
				<el-button  type="primary" @click="getPage">
					<i class="el-icon-search mr-2" />查询
				</el-button>
			</div>
		</el-header>
		<el-main class="nopadding">
			<el-table ref="table" :data="paginatedData" border>
				<el-table-column prop="fileName" label="文件名称"/>
				<el-table-column prop="fileUrl" label="文件地址" width="220" align="center">
					<template #default="{row}">
						<div class="file-link">
							<el-image
								v-if="isImageType(row.fileUrl)"
								style="width: 80px; height: 40px; cursor: pointer"
								:src="row.fileUrl"
								:preview-src-list="[row.fileUrl]"
								fit="contain"
								close-on-click-modal
								preview-teleported
								:z-index="9999"
							>
								<template #error>
									<div class="text-gray-400">预览加载失败</div>
								</template>
							</el-image>
							<a
								v-else
								:href="row.fileUrl"
								target="_blank"
								class="text-blue-600 hover:text-blue-800 truncate"
							>
								{{ getFileName(row.fileUrl) }}
								<el-tag size="mini" :type="getFileTagType(row.fileUrl)" class="ml-2">
									{{ getFileExtension(row.fileUrl) }}
								</el-tag>
							</a>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="pusherName" label="推送人" width="150"/>
				<el-table-column label="接收人" width="200">
					<template #default="{row}">
						<el-button type="text" @click="openRecipientsDialog(row)">
							{{ formatRecipientsName(row.oaDocumentFollowupUserParamList) }}
						</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="pushTime" label="推送时间" width="180"/>
				<el-table-column label="操作" width="220">
					<template #default="{row}">
						<el-button size="small" @click="edit(row)">编辑</el-button>
						<el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="search.page"
				:page-size="search.pageSize"
				layout="total, prev, pager, next"
				:total="total">
			</el-pagination>

			<!-- 接收人弹窗 -->
			<el-dialog title="接收人信息" v-model="recipientsDialogVisible" width="600px">
				<el-table :data="recipientsData" border>
					<el-table-column prop="approverName" label="接收人名称"/>
					<el-table-column label="消息状态" prop="messageStatus">
						<template #default="{row}">
							<span v-if="row.messageStatus === '0'" :style="{ color: 'red' }">未读</span>
							<span v-else-if="row.messageStatus === '1'" :style="{ color: 'green' }">已读</span>
							<span v-else-if="row.messageStatus === '2'" :style="{ color: 'blue' }">收到</span>
						</template>
					</el-table-column>
				</el-table>
			</el-dialog>

			<!-- 表单弹窗 -->
			<el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
				<el-form :model="formData" label-width="100px" ref="formRef" :rules="rules">
					<el-form-item label="附件上传" prop="file">
						<el-upload
							:action="action"
							:file-list="fileList"
							:before-upload="beforeUpload"
							:on-success="handleSuccess"
						>
							<el-button type="primary">点击上传</el-button>
							<template #tip>
								<div class="el-upload__tip">支持格式：doc/pdf/图片/视频（单文件≤50MB）</div>
							</template>
						</el-upload>
					</el-form-item>
					<el-form-item v-if="dialogTitle === '编辑文件贯彻'" label="文件名称" prop="fileName">
						<el-input v-model="formData.fileName" placeholder="请输入文件名称" />
					</el-form-item>
<!--					{{userInfoList}}-->
					<el-form-item label="接收人" prop="oaDocumentFollowupUserParamList">
						<multi-select-personnel-module
							ref="multiSelectPersonnelModule"
							:userInfoList="userInfoList"
							:mode="true"
							@success="onApproverSelected"

						></multi-select-personnel-module>
<!--						:resType="1"-->
					</el-form-item>
				</el-form>

				<template #footer>
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="submitForm">提交</el-button>
				</template>
			</el-dialog>
		</el-main>
	</el-container>
</template>

<script>
import multiSelectPersonnelModule from '@/views/module/selectUserDialogGetUserDeptId.vue';
import { FINANCE_CODES } from '@/config/statusCodes'

export default {
	name: 'DocumentFollowUp',
	components: {
		multiSelectPersonnelModule
	},
	data() {
		return {
			search: {
				page: 1,
				pageSize: 15
			},
			total: 0,
			paginatedData: [],
			action: '/capi/get/uploadFileByCode?code=' + FINANCE_CODES.DOCUMENT_FOLLOW_UP,
			dialogVisible: false,
			dialogTitle: '',
			userInfo: {},
			userInfoList: [],
			formData: {
				id: null,
				leader: '',
				file: null,
				fileUrl: '',
				oaDocumentFollowupUserParamList: []
			},
			fileList: [],
			users: [],
			rules: {
				leader: [{required: true, message: '请选择负责人'}],
				fileName: [{required: true, message: '请填写文件名称'}],
				recipientsId: [{type: 'array', required: true, message: '至少选择1位必看人员'}],
				file: [{required: true, message: '请上传文件'}],
				oaDocumentFollowupUserParamList: [{required: true, message: '请选择接收人'}],
			},
			recipientsDialogVisible: false,
			recipientsData: [],
		}
	},
	mounted() {
		this.getUsers();
		this.userInfo = this.$TOOL.data.get("USER_INFO");
		console.log('userInfo', this.userInfo)
		this.getPage();
	},
	methods: {
		onApproverSelected(selectedUsers) {
			console.log('selectedUsers:', selectedUsers);
			// if (selectedUsers && selectedUsers.length > 0) {
				this.formData.oaDocumentFollowupUserParamList = selectedUsers.map(user => ({
					recipientId: user.userId,
					recipientName: user.userName,
				}));
			// }
			console.log('this.ApproversFormData', this.formData);
		},
		handleSizeChange(newSize) {
			this.search.pageSize = newSize;
			this.getPage();
		},
		handleCurrentChange(newPage) {
			this.search.page = newPage;
			this.getPage();
		},
		getUsers() {
			this.$API.office.documentationFollowThrough.getUserInfoAll.get().then(res => {
				this.users = res.data;
				console.log('users', this.users)
			}).catch(err => {
				this.$message.error('获取用户失败')
			})
		},
		getPage() {
			this.$API.office.documentationFollowThrough.getByPusherId.get({
				pusherId: this.userInfo.id,
				page: this.search.page,
				pageSize: this.search.pageSize
			}).then(res => {
				console.log('res.data.list', res.data.list)
				this.paginatedData = res.data.list;
				this.total = parseInt(res.data.total, 10);
				console.log('paginatedData', this.paginatedData)
			}).catch(err => {
				this.$message.error('分页失败')
			})
		},
		beforeUpload(file) {
			const isLt50M = file.size / 1024 / 1024 < 50
			if (!isLt50M) {
				this.$message.error('文件大小不能超过50MB!')
				return false
			}
			this.formData.fileName = file.name
			console.log('beforeUpload', file)
			return true
		},
		handleSuccess(response, file) {
			console.log('response', response)
			console.log('response.url', response.redirect)
			this.formData.fileUrl = response.redirect
			this.fileList = [{name: file.name, url: response.redirect}];
		},
		add() {
			this.formData = {};
			this.fileList = [];
			this.userInfoList = [];
			this.dialogTitle = '添加文件贯彻';
			this.dialogVisible = true;
		},
		openDialog(row){
			console.log('111111111',row)
		},
		edit(row) {
			this.userInfoList = [];
			this.userInfoList = row.oaDocumentFollowupUserParamList.map(item => item.recipientId);
			console.log('row', JSON.parse(JSON.stringify(row)));
			this.dialogTitle = '编辑文件贯彻';
			if (row.fileUrl) {
				this.formData.fileUrl = row.fileUrl;
				this.fileList = [{name: row.fileName, url: row.fileUrl}];
			}
			this.formData = {...row};

			this.dialogVisible = true;
		},
		openRecipientsDialog(row) {
			this.$API.office.documentationFollowThrough.getByRecipientsIdAndId.get({
				pusherId: this.userInfo.id,
				id: row.id
			}).then(res => {
				this.recipientsData = res.data;
				this.recipientsDialogVisible = true;
			}).catch(err => {
				this.$message.error('获取接收人状态信息失败');
			});
		},
		submitForm() {
			if (!this.fileList || this.fileList.length === 0) {
				this.$message.error('请上传至少一个文件');
				return;
			}

			if (!Array.isArray(this.formData.oaDocumentFollowupUserParamList) ||
				this.formData.oaDocumentFollowupUserParamList.length === 0) {
				this.$message.error('请至少选择一位有效的必看人员');
				return;
			}

			let params = {
				pusherId: this.userInfo.id,
				oaDocumentFollowupUserParamList: this.formData.oaDocumentFollowupUserParamList,
				fileUrl: this.formData.fileUrl,
				fileName: this.formData.fileName
			};

			if (this.formData.id) {
				params.id = this.formData.id;
				this.$API.office.documentationFollowThrough.update.postPro(params)
					.then(() => this.getPage())
					.catch(() => this.$message.error('编辑失败'));
			} else {
				this.$API.office.documentationFollowThrough.add.postPro(params)
					.then(() => this.getPage())
					.catch(() => this.$message.error('添加失败'));
			}

			this.dialogVisible = false;
			this.$message.success('操作成功');
		},
		handleDelete(id) {
			this.$confirm('确认删除该记录？', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$API.office.documentationFollowThrough.deleteById.del({id})
					.then(() => {
						this.getPage();
						this.$message.success('删除成功');
					})
					.catch(() => this.$message.error('删除失败'));
			}).catch(err => {

			})
		},
		getFileExtension(url) {
			const ext = url?.split('.').pop().toLowerCase() || '';
			const mimeMap = {
				png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif',
				pdf: 'application/pdf', doc: 'application/msword',
				docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
			};
			return mimeMap[ext] ? ext : 'file';
		},
		isImageType(url) {
			const imageTypes = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp'];
			return imageTypes.includes(this.getFileExtension(url));
		},
		getFileName(url) {
			return url?.split('/').pop().substring(0, 20) + (url?.length > 20 ? '...' : '') || '';
		},
		getFileTagType(url) {
			const typeMap = {
				pdf: 'danger', doc: 'primary', docx: 'primary',
				xls: 'warning', xlsx: 'warning', ppt: 'success', pptx: 'success'
			};
			return typeMap[this.getFileExtension(url)] || 'info';
		},
		formatRecipientsName(oaDocumentFollowupUserParamList) {
			if (!Array.isArray(oaDocumentFollowupUserParamList)) return '';

			const names = oaDocumentFollowupUserParamList
				.filter(item => item?.recipientName)
				.map(item => item.recipientName);

			if (names.length === 0) return '无接收人';

			let result = names.join('、');
			const commaCount = (result.match(/、/g) || []).length;
			if (commaCount > 5) {
				result = `${names.slice(0, 6).join('、')}等${names.length}人`;
			}
			return result;
		}
	}
}
</script>

<style scoped>
.file-link {
	@apply flex items-center;
}
.file-thumbnail {
	@apply w-16 h-16 rounded cursor-pointer shadow hover:shadow-md transition-all;
}
.el-image__error {
	@apply flex items-center justify-center bg-gray-100;
}
.el-tag {
	@apply transform scale-90;
}
.recipients-button {
	white-space: pre-line;
	word-break: break-all;
	text-align: left;
	line-height: 1.5;
	max-width: 200px;
}
.nopadding {
	padding: 0;
}
</style>
